package sentinel;

import java.lang.reflect.InvocationTargetException;

public class Class05_rongduan {

    enum States {
            OPEN,
            HALFOPEN,
            CLOSE
        }
        public static int count = 0;//慢调用数
        public static long slowtime = 90;//慢调用时间
        public static States state = States.CLOSE;
        public static long timeStamp = System.currentTimeMillis();
        public static long rongduanTime = 1000;//熔断时间 ms
        public static int slowCount = 3;//规定慢调用次数
        public static long dotime;

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, InterruptedException {
        while(true){
            Class<?> clazz =  Class.forName("sentinel.Class04_TokenBucket");
            Class04_TokenBucket obj =  (Class04_TokenBucket) clazz.getConstructor().newInstance();

            try{
                long now = System.currentTimeMillis();
                if(state == States.OPEN && now - timeStamp >= rongduanTime){
                    state = States.HALFOPEN;
                }
                System.out.println(state);

                if(state == States.OPEN){
                    throw new RongduanbExpection();
                }
                    obj.test();
                long timeAfter = System.currentTimeMillis();
                dotime = timeAfter - now;
                if(dotime >= slowtime){
                    count++;
                }
            }catch (RongduanbExpection e){
                Thread.sleep(100);
                System.out.println("熔断异常");
            }catch (Exception e){
                e.printStackTrace();
            }
            finally {
                long ct = System.currentTimeMillis();

                if(state == States.HALFOPEN){
                    if(dotime >= slowtime){
                        state = States.OPEN;
                    }else {
                        state = States.CLOSE;
                        count = 0;
                    }
                    if(ct - timeStamp >= rongduanTime){
                        timeStamp = ct;
                    }
                }else if(state == States.CLOSE){
                    if(count >= slowCount){
                        state =  States.OPEN;
                    }
                }
                System.out.println();
            }
        }
    }
}
